/*
 * private-sreg.c
 *
 *  Created on: Sep 27, 2009
 *      Author: Orlando Arias
 *	   License: GPLv3
 *
 *   libhd44780 for Arduino Systems
 *   Copyright (C) 2009  Orlando Arias
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "common/common_private.h"
#include "WProgram.h"

#include "private-sreg.h"


void lcds_sendRaw(sLCD *l, uint8_t data, uint8_t rs_state){
	/*
	 *  The LCD is operating in 4 bit mode. Data sent to the
	 *  shift register includes four bits and the state of
	 *  RS as follows
	 *  [DB] [DB] [DB] [DB] [RS]
	 *
	 *  the data is then processed and sent accordingly.
	 */

	// send highest nibble and RS state
	lcds_SIPO(l, ((data >> 3) & 0x1E) | rs_state);
	lcd_triggerStrobe(l->strobe);
	// send lowest nibble and RS state
	lcds_SIPO(l, (data << 1) | rs_state);
	lcd_triggerStrobe(l->strobe);
}

void lcds_SIPO(sLCD *l, uint8_t data){
	for (uint8_t i = 0; i<=4; i++){
		// Send data starting with the most significant bit
		// TODO: Change documentation on how to construct circuit
		// digitalWrite(l->datapin, (data >> (4 - i)) & 0x01);
		digitalWrite(l->datapin, data & 0x01);
		data >>= 1;
		// Allow for the shift register's propagation delay
		delayMicroseconds(SREG_PROP_DELAY);
		// Drive clock high to commit data
		digitalWrite(l->clock, HIGH);
		// Allow for shift register's proper clock pulse
		delayMicroseconds(SREG_PULSE_DELAY);
		// Drive clock low
		digitalWrite(l->clock, LOW);
	}
}
